package dbgroup02.dao.db2;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import dbgroup02.bean.CheckInInfo;
import dbgroup02.dao.CheckInInfoDao;

public class CheckInInfoDB2Dao implements CheckInInfoDao {

	private JdbcTemplate jdbcTemplate;

	ParameterizedRowMapper<CheckInInfo> getChechInInfoMapper = new ParameterizedRowMapper<CheckInInfo>() {
		@Override
		public CheckInInfo mapRow(ResultSet resultSet, int arg1)
				throws SQLException {
			CheckInInfo checkInInfo = new CheckInInfo();
			checkInInfo.setIdCheckInInfo(resultSet.getInt(1));
			checkInInfo.setIdBoardingPass(resultSet.getInt(2));
			checkInInfo.setIdFlight(resultSet.getInt(3));
			checkInInfo.setIdStaff(resultSet.getInt(4));
			return checkInInfo;
		}
	};

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void addCheckInInfo(CheckInInfo checkInInfo) {
		jdbcTemplate
				.update("INSERT INTO "
						+ CheckInInfoDao.SCHEMA
						+ ".CHECKIN_INFO (BOARDING_PASS_ID, FLIGHT_ID, STAFF_ID)"
						+ "VALUES (?,?,?)",
						new Object[] { checkInInfo.getIdBoardingPass(),
								checkInInfo.getIdFlight(),
								checkInInfo.getIdStaff() });
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
	public CheckInInfo getCheckInInfo(int idCheckInInfo) {
		List<CheckInInfo> result = jdbcTemplate.query("SELECT * FROM "
				+ CheckInInfoDao.SCHEMA
				+ ".CHECKIN_INFO WHERE CHECKIN_INFO_ID = ?",
				new Object[] { idCheckInInfo }, getChechInInfoMapper);

		if (result.size() > 0)
			return result.get(0);
		else
			return null;

	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
	public CheckInInfo getCheckInfoByFlight(int idFlight) {
		List<CheckInInfo> result = jdbcTemplate.query("SELECT * FROM "
				+ CheckInInfoDao.SCHEMA + ".CHECKIN_INFO WHERE FLIGHT_ID = ?",
				new Object[] { idFlight }, getChechInInfoMapper);

		if (result.size() > 0)
			return result.get(0);
		else
			return null;

	}

}
